package org.blogspot.t0yv0.marcalog.controller

import java.io._
import com.google.appengine.api.blobstore._
import org.marc4j._
import org.marc4j.marc._
import org.blogspot.t0yv0.marcalog.model._
import org.blogspot.t0yv0.marcalog.util._

sealed class ParseTask(blob: BlobKey) extends Task {

  def this() = this(new BlobKey(""))

  override val parameters =
    Map(("blob", blob.getKeyString));

  override def execute(ctx: HttpContext, pm: DataManager) {
    val blob   = new BlobKey(ctx.request.getParameter("blob"))
    val reader = new BlobstoreInputStream(blob);
    val bstore = BlobstoreServiceFactory.getBlobstoreService();
    try {
      val stream = new EagerInputStream(reader);
      val marc   = new MarcStreamReader(stream, "MARC8");
      var n      = 0;
      var w      = new StringWriter()
      while (marc.hasNext) {
        val record = marc.next;
        val (title, person, isbn) = Marc.parse(record);
        w.write(title);
        w.write("\n");
        w.write(person);
        w.write("\n");
        w.write(isbn);
        w.write("\n");
        n = n + 1;
        if (n % 100 == 0) {          
          Tasks.schedule(new InsertTask(w.toString));
          w = new StringWriter();
          n = 0;          
        }
      }
      if (n > 0) {
        Tasks.schedule(new InsertTask(w.toString));
      }
    } finally {
      reader.close();
      bstore.delete(blob);
    }
  }
}
